<?php
/** 
*
* @package phpBB3
* @version $Id: session.php,v 1.242 2006/11/12 15:35:43 acydburn Exp $ 
* @copyright (c) 2005 phpBB Group 
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/

/**
* Session class
* @package phpBB3
*/
class session
{
	var $page = array();
	var $data = array();
	var $browser = '';
	var $host = '';
	var $session_id = '';
	var $ip = '';
	var $load = 0;
	var $time_now = 0;
	var $update_session_page = true;

	/**
	* Extract current session page
	*
	* @param string $root_path current root path (phpbb_root_path)
	*/
	function extract_current_page($root_path)
	{
		$page_array = array();

		// First of all, get the request uri...
		$script_name = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : getenv('PHP_SELF');
		$args = (!empty($_SERVER['QUERY_STRING'])) ? explode('&', $_SERVER['QUERY_STRING']) : explode('&', getenv('QUERY_STRING'));

		// If we are unable to get the script name we use REQUEST_URI as a failover and note it within the page array for easier support...
		if (!$script_name)
		{
			$script_name = (!empty($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : getenv('REQUEST_URI');
			$page_array['failover'] = 1;
		}

		// Replace backslashes and doubled slashes (could happen on some proxy setups)
		$script_name = str_replace(array('\\', '//'), '/', $script_name);

		// Now, remove the sid and let us get a clean query string...
		foreach ($args as $key => $argument)
		{
			if (strpos($argument, 'sid=') === 0 || strpos($argument, '_f_=') === 0)
			{
				unset($args[$key]);
				break;
			}
		}

		// The following examples given are for an request uri of {path to the phpbb directory}/adm/index.php?i=10&b=2

		// The current query string
		$query_string = trim(implode('&', $args));

		// basenamed page name (for example: index.php)
		$page_name = basename($script_name);
		$page_name = urlencode(htmlspecialchars($page_name));

		// current directory within the phpBB root (for example: adm)
		$root_dirs = explode('/', str_replace('\\', '/', realpath($root_path)));
		$page_dirs = explode('/', str_replace('\\', '/', realpath('./')));
		$intersection = array_intersect_assoc($root_dirs, $page_dirs);

		$root_dirs = array_diff_assoc($root_dirs, $intersection);
		$page_dirs = array_diff_assoc($page_dirs, $intersection);

		$page_dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);

		if ($page_dir && substr($page_dir, -1, 1) == '/')
		{
			$page_dir = substr($page_dir, 0, -1);
		}

		// Current page from phpBB root (for example: adm/index.php?i=10&b=2)
		$page = (($page_dir) ? $page_dir . '/' : '') . $page_name . (($query_string) ? "?$query_string" : '');

		// The script path from the webroot to the current directory (for example: /phpBB2/adm/) : always prefixed with / and ends in /
		$script_path = trim(str_replace('\\', '/', dirname($script_name)));

		// The script path from the webroot to the phpBB root (for example: /phpBB2/)
		$script_dirs = explode('/', $script_path);
		array_splice($script_dirs, -sizeof($page_dirs));
		$root_script_path = implode('/', $script_dirs) . (sizeof($root_dirs) ?  '/' . implode('/', $root_dirs) : '');

		// We are on the base level (phpBB root == webroot), lets adjust the variables a bit...
		if (!$root_script_path)
		{
			$root_script_path = ($page_dir) ? str_replace($page_dir, '', $script_path) : $script_path;
		}

		$script_path .= (substr($script_path, -1, 1) == '/') ? '' : '/';
		$root_script_path .= (substr($root_script_path, -1, 1) == '/') ? '' : '/';

		$page_array += array(
			'page_name'			=> $page_name,
			'page_dir'			=> $page_dir,

			'query_string'		=> $query_string,
			'script_path'		=> str_replace(' ', '%20', htmlspecialchars($script_path)),
			'root_script_path'	=> str_replace(' ', '%20', htmlspecialchars($root_script_path)),

			'page'				=> $page
		);

/*
		if (!file_exists($page_name))
		{
			trigger_error('You are on a page that does not exist!', E_USER_ERROR);
		}
*/

		return $page_array;
	}

	/**
	* Start session management
	*
	* This is where all session activity begins. We gather various pieces of
	* information from the client and server. We test to see if a session already
	* exists. If it does, fine and dandy. If it doesn't we'll go on to create a 
	* new one ... pretty logical heh? We also examine the system load (if we're
	* running on a system which makes such information readily available) and
	* halt if it's above an admin definable limit.
	*
	* @param bool $update_session_page if true the session page gets updated.
	*			This can be set to circumvent certain scripts to update the users last visited page.
	*/
	function session_begin($update_session_page = true)
	{
		global $db, $config, $root_path;

		// Give us some basic informations
		$this->time_now				= time();
		$this->update_session_page	= $update_session_page;
		$this->browser				= (!empty($_SERVER['HTTP_USER_AGENT'])) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
		$this->host					= (!empty($_SERVER['HTTP_HOST'])) ? (string) $_SERVER['HTTP_HOST'] : 'localhost';
		$this->page					= $this->extract_current_page($root_path);

		// set up sessions stuff
		session_name('sid');
		session_set_cookie_params(3600 * 24); // cookies lifetime, 1 day
		session_cache_expire(60 * 24); // cache expire in one day too
		session_cache_limiter('nocache'); // disable caching
		session_start();
		$this->session_id = session_id();
		// Why no forwarded_for et al? Well, too easily spoofed. With the results of my recent requests
		// it's pretty clear that in the majority of cases you'll at least be left with a proxy/cache ip.
		$this->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
		$this->load = false;
		
		// Is session_id is set or session_id is set and matches the url param if required
		if (!empty($_SESSION))
		{

			return true;
		}
		else{
		    return $this->session_create();	
		}
		
	}
	/**
	* Create a new session
	*
	* If upon trying to start a session we discover there is nothing existing we
	* jump here. Additionally this method is called directly during login to regenerate
	* the session for the specific user. In this method we carry out a number of tasks;
	* garbage collection, (search)bot checking, banned user comparison. Basically
	* though this method will result in a new session for a specific user.
	*/
	function session_create($user_id = false, $set_admin = false, $persist_login = false, $viewonline = true)
	{
		global $db, $config, $cache, $root_path;

		$this->data = array();

		session_regenerate_id(); // sets new id

		
		
		/**
		* Here we do a bot check, oh er saucy! No, not that kind of bot
		* check. We loop through the list of bots defined by the admin and
		* see if we have any useragent and/or IP matches. If we do, this is a
		* bot, act accordingly
		*/		
		$bot = false;
		
		// Create or update the session
		$sql_ary = array(
			'session_admin'			=> $set_admin ,
			'session_page'			=> (string) substr($this->page['page'], 0, 199),			
		);

		foreach ($sql_ary as $name => $val)
		{
			$_SESSION[$name] = $val;
		}

		return true;
	}

	/**
	* Kills a session
	*
	* This method does what it says on the tin. It will delete a pre-existing session.
	* It resets cookie information (destroying any autologin key within that cookie data)
	* and update the users information from the relevant session data. It will then
	* grab guest user information.
	*/
	function session_kill()
	{
		global $db, $config, $root_path;
		
		$_SESSION = array();
		unset($_SESSION);
		print_r($_SESSION);
		return true;
	}



	/**
	* Authentication plug-ins is largely down to Sergey Kanareykin, our thanks to him.
	*/
	function login($username, $password, $autologin = false, $viewonline = 1, $admin = 1)
	{
		global $config, $db, $root_path;

		if($username=="Martin" && $password == "sch31d3l"){			
			$result = $this->session_create(1, 1, $autologin, $viewonline);			
			return true;
		}

		return false;
	}
}


/**
* Base user class
*
* This is the overarching class which contains (through session extend)
* all methods utilised for user functionality during a session.
*
* @package phpBB3
*/
class user extends session
{
	var $lang = array();

	var $lang_name;
	var $lang_path;

	var $cena;
	var $sleva;

	/**
	* Setup basic user-specific items (style, language, ...)
	*/
	function setup($lang_set = false, $style = false)
	{
		global $db, $template, $config, $root_path, $cache;

		if ($this->data['user_id'] != ANONYMOUS)
		{
			$this->lang_name = (file_exists($root_path . 'language/' . $this->data['user_lang'] . '/common.php')) ? $this->data['user_lang'] : $config['default_lang'];
			$this->lang_path = $root_path . 'language/' . $this->lang_name . '/';

		}
		else
		{
			$this->lang_name = $config['default_lang'];
			$this->lang_path = $root_path . 'language/' . $this->lang_name . '/';
		}

		// We include common language file here to not load it every time a custom language file is included
		$lang = &$this->lang;
//		if ((include $this->lang_path . 'common.php') === false)
		//{
//			die('Language file ' . $this->lang_path . 'common.php  couldn\'t be opened.');
		//}

		
		
		// Set up additional things
		if (isset($this->data['user_vo']) && $this->data['user_vo'])
		{
			$this->cena		= 'cena_vo';
			$this->sleva	= 'sleva_vo';
		}
		else
		{
			$this->cena		= 'cena_mo';
			$this->sleva	= 'sleva_mo';
		}

		return;
	}



	/**
	* checks user for admin
	*/
	function is_admin()
	{
		return (int) $this->data['user_type'] == USER_FOUNDER;
	}
	
	/**
	* set menu
	*/
	function set_menu($menu = PNEU)
	{
		$_SESSION['session_menu'] = $menu;
	}
	
	/**
	* get menu
	*/
	function get_menu($default = PNEU)
	{
		return isset($_SESSION['session_menu']) ? $_SESSION['session_menu'] : $default;
	}
}

?>
